package com.kd.sms.provider.aliyun;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.kd.sms.config.SmsProperties;
import com.kd.sms.model.req.SendSmsReq;
import com.kd.sms.model.resp.ISmsResp;
import com.kd.sms.model.resp.SmsRespData;
import com.kd.sms.provider.AbstractProvider;
import com.kd.sms.provider.aliyun.model.AliYunSmsResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AliYunSmsProvider extends AbstractProvider {

    protected Client client;

    static {
        Map<String, String> map = new HashMap<>();
        map.put("register", "SMS_203215001");
        templateIdMap = map;
    }

    public AliYunSmsProvider(SmsProperties smsProperties, ApplicationEventPublisher applicationEventPublisher) throws Exception {
        super(smsProperties, applicationEventPublisher);
    }

    @Override
    protected void initialize() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(this.smsProperties.getSecretId());
        config.setAccessKeySecret(this.smsProperties.getSecretKey());
        config.setEndpoint(this.smsProperties.getEndpoint());

        this.client = new Client(config);
    }

    @Override
    @SuppressWarnings("unchecked")
    public ISmsResp<SmsRespData> sendSms(SendSmsReq req) throws Exception {
        String templateId = this.resolveTemplateId(req);
        if (templateId == null || templateId.isEmpty()) {
            throw new IllegalArgumentException("未配置业务对应的短信模板ID");
        }

        log.info("短信发送请求参数: {}", objectMapper.writeValueAsString(req));

        String signName = req.getSignName() !=null && !req.getSignName().isEmpty() ? req.getSignName() : this.getDefSignName();
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(req.getMobile());
        request.setSignName(signName);
        request.setTemplateCode(templateId);
        request.setTemplateParam(this.objectMapper.writeValueAsString(req.getParams()));

        SendSmsResponse resp = this.client.sendSms(request);
        log.info("短信发送响应结果: {}", objectMapper.writeValueAsString(resp));

        ISmsResp<SmsRespData> smsResp = new AliYunSmsResp<>(resp.getBody(), SmsRespData.class);
        this.publishSendSmsEvent((ISmsResp<SmsRespData>) resp);

        return smsResp;
    }

    @Override
    protected String resolveTemplateId(SendSmsReq req) {
        return templateIdMap.getOrDefault(req.getBiz(), null);
    }
}
